<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: ModelfieldController.php 465 2012-02-12 05:33:23Z beimuaihui $
 */



class System_ModelfieldController extends Baogg_Controller_Action {

	function init() {
		Zend_Loader::loadClass ( 'ModelField' );
		$this->modelField = new ModelField ( );

	}

	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;
		
		$params=$this->getRequest()->getParams();
		$model_id=@$params['model_id'];
		$form_url=$params;
		BAOGG_LANGUAGE::loadFile("model");
		
		
		Zend_Loader::loadClass("Baogg_View_Extgrid");
		
		$cm=array();
		$cm['field_id']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_PK) ;
		$cm['field_name']=array("sortable"=>true);
		//$cm['model_name']=array("sortable"=>true);
		$cm['show_name']=array("sortable"=>true);
		$cm['field_type']=array("sortable"=>true);
		$cm['field_view']=array("sortable"=>true);
		$cm['field_options']=array("sortable"=>true);
		$cm['init_value']=array("hidden"=>true);
		$cm['tips']=array("hidden"=>true);		
		$cm['check_pattern']=array("hidden"=>true);
		$cm['check_error']=array("hidden"=>true);	
		$cm['field_key']=array("sortable"=>true);	
		$cm['model_pid']=array("sortable"=>true);	
		$cm['is_basic']=array("sortable"=>true);		
		$cm['state']=array("sortable"=>true);
		$cm['ordering']=array("sortable"=>true);
		
		//$cm['sub_table']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_SUBTABLE) ; //Baogg_View_Extgrid::;
		
		$form_url['action']="data";
		$grid=new Baogg_View_Extgrid($form_url, $cm);
		$grid->setSelectionModel(true);
		$grid->setRowNumberer(true);
		$grid->addExistButtons(array('add','remove','query'),array('edit','delete'));
		
		
	   $arr_field_type=include BAOGG_ROOT.'config/qa/field_type.php';
	   $store_field_view=array(array('',Baogg_Language::get('please_select')));
        foreach((array)$arr_field_type as $k=>$v){
            $store_field_view[]=array($k,$v['Label']);
        }

        
		$this->view->LANG=Zend_Json::encode($LANG);
		$this->view->grid = $grid->render();
		$this->view->model_id=$model_id;
		

		$Model=new Model();
		$rs_model=$Model->getOne($model_id);
		$model_name=(is_array($rs_model) && count($rs_model)>0)?$rs_model[0]['model_name']:"";
		
		$Dict=new Dict();
		$store_dict=$Dict->getCombo(array("state"=>1),array("sort"=>"ordering","dir"=>"asc"),null,array("dict_id","dict_name"));
		$store_dict=array_merge(array(array("0",BAOGG_LANGUAGE::get("please_select"))),$store_dict);
		
		$form_url['action']='add';
		$form=new Baogg_View_Extform(array("url"=>$form_url,"height"=>600,"width"=>600));
		
		$form->addItem(0,array('name'=>'model_name','xtype'=>'displayfield','fieldLabel'=>BAOGG_LANGUAGE::get('model_name'),'value'=>$model_name));
		$form->addItem(0,array('name'=>'field_name'));
		$form->addItem(0,array('name'=>'show_name'));		
		$form->addItem(0,array('name'=>'field_view','xtype'=>'combo','store'=>$store_field_view));
		$form->addItem(0,array('name'=>'dict_id','xtype'=>'combo','store'=>$store_dict));
		$form->addItem(0,array('name'=>'field_options','xtype'=>'textarea','validator'=>new Zend_Json_Expr('function(v){if(v==""){return true;} try{Ext.decode(v,false);return true;}catch(e){return false;}}')));
		$form->addItem(0,array('name'=>'init_value'));
		
		$form->addItem(1,array('name'=>'field_type'));
		$form->addItem(1,array('name'=>'field_null','xtype'=>'radiogroup','value'=>'YES','source'=>BAOGG_LANGUAGE::array2store(array("YES"=>"YES","NO"=>"NO"))));
		$form->addItem(1,array('name'=>'field_key','xtype'=>'combo','store'=>BAOGG_LANGUAGE::array2store(array(""=>BAOGG_LANGUAGE::get('please_select'),"PRI"=>"PRI","UNI"=>"UNI","MUL"=>"MUL"))));
		$form->addItem(1,array('name'=>'field_extra','xtype'=>'checkboxgroup', 'source'=>BAOGG_LANGUAGE::array2store(array("auto_increment"=>"auto_increment"))));
		
		$form->addItem(1,array('name'=>'tips'));
		$form->addItem(1,array('name'=>'check_pattern'));
		
		$rs_parent=$Model->getCombo(null,null,null,array('model_id','model_name'));
		//echo '<pre>'.__FILE__.__LINE__;print_r($rs_parent);exit;
		$form->addItem(1,array('name'=>'model_pid','xtype'=>'combo','store'=>$rs_parent));		
		
		$form->addItem(2,array('name'=>'is_basic','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));
		$form->addItem(2,array('name'=>'is_value','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));
		$form->addItem(2,array('name'=>'is_label','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));
		$form->addItem(2,array('name'=>'is_parent','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));
		$form->addItem(2,array('name'=>'state','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));
		$form->addItem(2,array('name'=>'ordering'));		
		$form->addItem(2,array('name'=>'model_id',"xtype"=>"hidden","hideLabel"=>true,'value'=>$model_id));	
		$form->addItem(2,array('name'=>'field_id',"xtype"=>"hidden","hideLabel"=>true));	
		
		$form->addExistButtons(array('-','save_grid','save_new','save','-','search','-','cancel'));//,'config','config'
		$this->view->form=$form;


	}

	/**
	 * The data action
	 */
	function dataAction() {
	    $post=$this->_request->getPost ();
	    $model_id=$this->_request->getParam('model_id');
	    $where=array();$order=array();$limit=array();
	   foreach((array)$post as $k=>$v){
	       if($k=="start" || $k=="limit"){
	           $limit[$k]=$v;
	       }else if($k=="sort" || $k=="dir"){
	           $order[$k]=$v;
	       }else{
	           if($k=="field_id"  ){
	               if($v && is_numeric($v)){
	                   $v=(int)$v;
	                   $where[$k]=$v;
	               }
	           }else{
	               $v='%'.$v.'%';
	               $where[$k]=$v;
	           }
	           
	       }
	   }
	   if(!$order){
	   		$order=array("sort"=>"ordering","dir"=>"asc");
	   }
	   $where['model_id']=(int)$model_id;
	   $rs_cnt=$this->modelField->getList($where,null,null,array('cnt'=>'count(*)'));
	   $data=$this->modelField->getList($where,$order,$limit);
	   //echo Baogg_Db::debugDb(Zend_Registry::get('db'));exit;
	   $this->view->grid = Zend_Json::encode(array("count"=>$rs_cnt[0]['cnt'],"data"=>$data));
	}

	
	/**
	 * The add action
	 */
	function addAction(){		
		$this->saveAction();		
	}
	
	/**
	 * The edit action
	 */
	function editAction() {
		$this->saveAction();
	}

	/**
	 * The delete action
	 */
	function deleteAction() {
        
	    $ret=array("success"=>false,"msg"=>"delete_fail");
	    $id = Baogg_Controller_Action::_getParam ( 'ids' );
		 
		   
		
		if ($this->modelField->_delete ( $id )){
			$ret['success'] = true;
			$ret["msg"]="delete_ok";
		}
		
		echo Baogg_Language::outputResult($ret);
		 $this->_helper->viewRenderer->setNoRender ();
	}
	
	function removeAction(){
		$this->deleteAction();
	}

	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
		
	    $ret=array("success"=>false,"msg"=>"save_fail");
	   
	    // echo '<pre>';print_r($this->modelField->info(ModelField::METADATA));exit;
	    //check form
		if (!$this->_request->isPost ())
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;
		}
		
		$formData = $this->_request->getPost ();

		if(!$formData)
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;     
		}
			
		$arr=$this->modelField->filterForm($formData);
        $action=$this->getRequest()->getParam('action');
		$rs = $this->modelField->getSame($arr);
		if($action=='edit'){
			//update record
			//$permission_type = 2;
			//echo '<pre>';print_r($rs);var_dump(count($rs));exit;
			if(!$rs ||  count($rs)==1 &&  $rs[0] == $arr["field_id"] ){
			    $this->modelField->_update($arr,$arr["field_id"]);
			    $ret['success'] = true;				
				$ret['msg'] = "save_ok";			
			}else{
				$ret['msg'] = "exist_same_record";
			}
			
		}else{
			//insert record
			//$permission_type = 1;			
			if($rs){				
				$ret['msg'] = "exist_same_record";
			}else{
			    unset($arr["field_id"]);
				$ret['success'] = $this->modelField->_insert($arr)>0?true:false;
				$ret['msg'] = "add_ok";
			}
		}

		$model=new Model();
		
		$ret['success']=$ret['success'] && $model->genExtTable($formData['model_id']);
		//$db=Zend_Registry::get("db");
		//echo Baogg_Db::debugDb($db);exit;
		echo Baogg_Language::outputResult($ret);
		
		$this->_helper->viewRenderer->setNoRender ();
		
		
	}

}
